package com.wutma.common.security.service;

import cn.hutool.core.lang.UUID;
import com.wutma.common.core.constants.CacheConstants;
import com.wutma.common.core.constants.JwtConstants;
import com.wutma.common.core.domain.entity.LoginUser;
import com.wutma.common.core.utils.JwtUtils;
import com.wutma.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 操作用户登录令牌-全局可用
 */
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String secrete, Integer identity, String nickName, String headImage) {

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
        claims.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(claims, secrete);
        // 将用户信息存入redis
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userId);
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(getTokenKey(userKey), loginUser, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);

        // 返回token
        return token;
    }

    /**
     * 刷新存储在redis中的token有效时间(调用范围在过滤器之后，接口之前 -> 在拦截器上使用)
     */
    public void extendToken(String token, String secret) {

        String userKey = getUserKey(token, secret);
        String tokenKey = getTokenKey(userKey);
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXPIRE_TIME, TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token, String secrete) {

        String userKey = getUserKey(token, secrete);
        if (userKey == null) {
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey), LoginUser.class);
    }

    public Long getUserId(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));  //获取jwt中的UserId
    }

    public String getUserKey(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token: {} 出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token: {} 出现异常", token, e);
            return null;
        }
        return claims;
    }

    private String getTokenKey(String userKey) {
        return CacheConstants.LOGIN_TOKEN + userKey;
    }

    public boolean deleteLoginUser(String token, String secrete) {
        String userKey = getUserKey(token, secrete);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }


    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
